package java_thinking.unit_16;

import java_thinking.net.mindview.util.ConvertTo;
import java_thinking.net.mindview.util.Generated;
import java_thinking.net.mindview.util.RandomGenerator;
import java_thinking.unit_15._15_3.Generator;

import java.util.Arrays;
import java.util.Random;

/**
 * @Desc:   二分查找:
 *          对没有排序的数组使用Arrays.binarySearch()会产生不可预知的结果
 * @author: cww
 * @DateTime: 2019/4/10 20:13
 */

public class E22_ArrayBinarySearch {
    public static void main(String[] args) {
        Generator<Integer> gen = new RandomGenerator.Integer(1000);
        int[] a = ConvertTo.primitive(Generated.array(new Integer[25], gen));
        System.out.println("Unsorted array: " + Arrays.toString(a));
        int location = Arrays.binarySearch(a, a[10]);
        System.out.println("Location of " + a[10] + " is " + location);
        if(location >= 0)
            System.out.println(", a[" + location + "] = " + a[location]);
        else
            System.out.println();
        location = Arrays.binarySearch(a, a[5]);
        System.out.println("Location of " + a[5] + " is " + location);
        if(location >= 0)
            System.out.println(", a[" + location + "] = " + a[location]);
    }
}

class BinarySearchTest {
    public static void main(String[] args) {
        Random r = new Random(47);
        int[] a = new int[5];
        for (int i =0; i <a.length; i++) {
            a[i] = r.nextInt(30);
        }
        System.out.println(Arrays.toString(a));
        //在查询key所在位置时，必须要先排序，不然即使存在，也找不到。如果是对象，对象需要实现Comparable接口
        System.out.println(Arrays.binarySearch(a,11));
        System.out.println(Arrays.binarySearch(a,1));
        Arrays.sort(a);
        System.out.println(Arrays.binarySearch(a,11));
    }
}